package com.sia.springcloud.selfInspection;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sia.springcloud.mapper.DeviceMapper;
import com.sia.springcloud.mapper.PointMapper;
import com.sia.springcloud.protocol.config.CollectApi;
import com.sia.springcloud.model.Device;
import com.sia.springcloud.model.Point;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: Sirius
 * @Date: 2021/12/31 21:55
 * @Description: 心跳自检任务
 **/
@Slf4j
@Component
public class SelfInspectionJob extends QuartzJobBean {

    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private PointMapper pointMapper;

    @Resource
    private CollectApi collectApi;




    /**
     * 心跳自检任务
     * <p>
     * 定时检查该微服务系统中是否存在数采状态为关闭但是处于数采状态的任务（属于该微服务协议的）
     * 只负责检查，不负责反馈
     *
     * @param context
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

        try {
            JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
            String protocolName = (String) jobDataMap.get("protocolName");

            QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
            deviceQueryWrapper.eq("collect", 0);
            deviceQueryWrapper.eq("protocol_name", protocolName);
            List<Device> deviceList = deviceMapper.selectList(deviceQueryWrapper);

            if (deviceList == null || deviceList.size() <= 0) {
                log.info("没有数采状态为关闭的设备");
            } else {
                for (Device device : deviceList) {
                    device.setMicroservice("nothing");
                    deviceMapper.updateById(device);

                    QueryWrapper<Point> pointQueryWrapper = new QueryWrapper<>();
                    pointQueryWrapper.eq("device_id", device.getId());
                    List<Point> pointList = pointMapper.selectList(pointQueryWrapper);
                    collectApi.stopCollect(device, pointList);
                }
            }
            log.info("心跳自检-----正常");
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("心跳自检-----异常");
        }

    }
}
